// src/store/authStore.ts
import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import {login} from '../services/user.js';
import {clearToken, setToken} from '../utils/auth';

export const useAuthStore = create((
    persist( // 持久化中间件
        (set) => ({
            isAuthenticated: false,
            user: null,
            loginAsync: async (params, callbacks) => {
                try {
                    const user = await login(params); // 1. 执行登录API调用
                    set({ isAuthenticated: true, user }); // 2. 更新状态
                    if (user && user.token) setToken(user.token);
                    callbacks?.onSuccess?.(); // 3. 如果提供了回调则执行
                    // ↑ ?. 是可选链操作符，不是zustand特有的
                } catch (error) {
                    // 调用错误回调
                    callbacks?.onError?.(error);
                    throw error; // 抛出错误让组件可以捕获
                }
            },
            logout: () => {
                set({ isAuthenticated: false, user: null });
                clearToken();
                sessionStorage.clear()
            },
        }),
        {
            name: 'user_info', // localStorage 的 key
            storage: createJSONStorage(() => sessionStorage), // 使用sessionStorage
            // 可选：只持久化特定字段
        }
    )
));
